#include  "drscontrol.h"
#include  "firewire.h"

void DRSControl::on_firewirePushButtonOpen_clicked(bool clicked)
{
	SInt32 result;
	if(!isFirewireOpen)
	{
		qDebug() << addTwoNumbers(3,2); //check the DLL is loaded.
		result = VHPDinit(&gVhpdReference);
		UInt32 numberOfDevices;
		result = VHPDscanDevices(gVhpdReference, &numberOfDevices);
		if(result < 0)
		{
			firewireDetermineError(result);
			errorDisplay(INFO,"VHPD",firewireErrorMsg);
		}
		else
		{

			qDebug() << numberOfDevices << "result" << result;
			for(int i=0; i<(int)numberOfDevices; i++)
			{
				UInt32 device;
				UInt32 node;
				UInt32 vendorId;
				UInt32 chipIdHigh;
				UInt32 chipIdLow;

				result = VHPDscanDeviceInfo(gVhpdReference, 
											i, 
											&device, 
											&node, 
											&vendorId, 
											&chipIdHigh, 
											&chipIdLow);

				qDebug("Scan result: %x, %x, %x, %x, %x\n", 
					device, node, vendorId, chipIdHigh, chipIdLow);
			}
			result = VHPDopen(gVhpdReference, 0);
		}
		if(result < 0)
		{
			firewireDetermineError(result);
			errorDisplay(INFO,"VHPD",firewireErrorMsg);
			VHPDclose(gVhpdReference);
		}
		else
		{
			result = VHPDsetupWriteBuffer(gVhpdReference, 0xFFFF, 
									 SI9475_LOW_ADDR, 0x1800);
		}
		if(result !=0)
		{
			firewireDetermineError(result);
			errorDisplay(1,"VHPD", firewireErrorMsg);
		}
		else
		{
			ui.firewireLabelStaus->setText("<font color='green'>Firewire Port OPEN</font.");
		}
		ui.firewirePushButtonOpen->setText("Close");
		isFirewireOpen = true;
	}
	else
	{
		/*CLOSE THE PORT*/
		ui.firewirePushButtonOpen->setText("Open");
		result = VHPDclose(gVhpdReference);
		qDebug() << "Close Port" << result;
		isFirewireOpen = false;
		ui.firewireLabelStaus->setText("<font color='red'>Firewire Port CLOSED</font>");
	}
}
void DRSControl::on_firewirePushButtonSend_clicked(bool clicked)
{
	QString str = ui.firewireLineEdit->text();
	QString tmp = str;
	tmp = tmp.prepend("TX: ");
	ui.firewireTextEdit->append(tmp);
	QByteArray d = str.toLatin1();
	char *c = d.data();
	int result;
	char respBuffer[2048];;
	if(str.contains("?",Qt::CaseInsensitive))
	{
		result = sendQuery(c,respBuffer,sizeof(respBuffer), get_address(), gVhpdReference);
		if(result < 0)
		{
			firewireDetermineError(result);
			if(result == -15)
			{
				ui.firewireTextEdit->append("RX: <NO RESPONSE>");
			}
			else
			{
				errorDisplay(INFO,"VHPDreference",firewireErrorMsg);
			}
		}
		else
		{
			qDebug() << "send query" << result << "resp=" << respBuffer;
			QString msg = respBuffer;
			msg = msg.remove("\n",Qt::CaseInsensitive);
			msg = msg.remove("\r",Qt::CaseInsensitive);
			msg = msg.prepend("RX: ");
			ui.firewireTextEdit->append(msg);
		}
	}
	else
	{
		result = sendCommand(c, get_address(), gVhpdReference);
		qDebug() << "send cmd";
		//ui.firewireTextEdit->append(c);
	}
	//unsigned long z = get_address();
	//qDebug() << z << " uLong";
}
int DRSControl::sendCommand(const char* cmd, unsigned long low_addr, VhpdReference ref)
{
	int result;

	char str[255];

	strcpy(str, cmd); 
    strcat(str, "\r\n");
	printf("writing string: %s", str);
	result = VHPDwriteBlock(ref, 0xFFFF, 
	    low_addr, str, strlen(str));
    //CHECK_RESULT("VHPDwriteBlock");

    return result;
}
int DRSControl::sendQuery(const char *query, char *resp, int respSize, unsigned long low_addr, VhpdReference ref)
{
    int result;

    result = sendCommand(query, low_addr, ref);
	qDebug() << "res after query send cmd" << result;
    if(result < 0)
    {
        return result;
    }

    result = VHPDgetQueuedResponse (ref, resp, respSize, 1000);
	qDebug() << "res after query send cmd" << result;
    return result;
}
void DRSControl::on_firewireLineEdit_returnPressed(void)
{
	bool c = true;
	qDebug() << "return pressed";
	on_firewirePushButtonSend_clicked(c);
	ui.firewireLineEdit->clear();
}
long DRSControl::get_address()
{
	unsigned long ret_val;
	int x = ui.firewireLowAddrComboBox->currentIndex();
	qDebug() << x;
	switch(x)
	{
	case 0:
		ret_val = SI9475_LOW_ADDR;
		break;
	case 1:
		ret_val = SI9475_COM1_RADIO_DROP_ADDR;
		break;
	default:
		ret_val = SI9475_LOW_ADDR;
		break;
	}
	return ret_val;
}
void DRSControl::firewireDetermineError(int err_val)
{
	qDebug() << err_val << " = error Val ";
	if(err_val == 0)
	{
		firewireErrorMsg = "No Error";
	}
	else
	{
		switch(err_val)
		{
		case -1:
			firewireErrorMsg ="Error while initializing, or initialization was not completed before this function was called.";
			break;
		case -2:
			firewireErrorMsg = "Error closing the unit";
			break;
		case -3:
			firewireErrorMsg = "Error opening";
			break;
		case -4:
			firewireErrorMsg = "Error reading";
			break;
		case -5:
			firewireErrorMsg = "Error writing";
			break;
		case -6:
			firewireErrorMsg = " There is an error in the configuration.";
			break;
		case -7:
			firewireErrorMsg = "The reference passed to the function was invalid.";
			break;
		case -8:
			firewireErrorMsg = "A bad parameter was passed.";
			break;
		case -9:
			firewireErrorMsg = "This functionality is not implemented.";
			break;
		case -10:
			firewireErrorMsg = "There is not enough memory available to perform the operation.";
			break;
		case -11:
			firewireErrorMsg = "There are no devices remaining.";
			break;
		case -12:
			firewireErrorMsg = "The buffer passed in was too small.";
			break;
		case -13:
			firewireErrorMsg = "There is no data available. This is not necessarily an error.";
			break;
		case -14:
			firewireErrorMsg = "The thread is already running.";
			break;
		case -15:
			firewireErrorMsg = "Timeout processing request.";
			break;
		default:
			firewireErrorMsg = "Error Unknown";
			break;
		}
	}
}
